
// ignore_for_file: constant_identifier_names

import 'dart:async';
import 'dart:ffi';

import 'package:flutter/material.dart';

import 'camera/camera_page.dart';
import 'my_home_page.dart';
import 'page/mine_page/mine_page.dart';
import 'player_page.dart';
import 'finance/finance_page.dart';
import 'video_page/video_list.dart';
import 'widget/photo_picker.dart';

/// Route页面导航最重要的代码
class MyRoute extends RouterDelegate<List<RouteSettings>>
    with ChangeNotifier, PopNavigatorRouterDelegateMixin<List<RouteSettings>> {

  final List<Page> _pages = [];
  // final是惰性检查机制, 在程序运行的时候才检查值. const在编译的时候就会检查!
  static const String mainPage = '/main';
  static const String secondPage = '/second';
  static const String playerPage = '/player';
  static const String videoListPage = '/video_list';
  static const String minePage = '/fragment_dou';
  static const String photoPicker = '/photo_picker';
  static const String cameraPage = '/camera';
  static const String key = 'key';
  static const String value = 'value';

  static const String key_url = 'url';
  static const String key_height = 'height';
  static const String key_width = 'width';

  late Completer<Object?> _boolResultComplete;

  MyRoute () {
//    _pages.add(_createPage(const RouteSettings(name: mainPage, arguments: [])));
  }

  @override
  Widget build(BuildContext context) {
    return Navigator(
      key: navigatorKey,
      pages: List.of(_pages),
      onPopPage: _onPopPage,);
  }

  @override
  GlobalKey<NavigatorState> get navigatorKey => GlobalKey<NavigatorState>();

  @override
  Future<void> setNewRoutePath(List<RouteSettings> configuration) async{
  }

  void replace ({required String name, dynamic args}) {
    if (_pages.isNotEmpty) {
      _pages.removeLast();
    }
    push(name: name, args: args);
  }

  @override
  Future<bool> popRoute({Object? params}) {
    if (params != null) {
      _boolResultComplete.complete(params);
    }

    if (_canPop()) {
      _pages.removeLast();
      notifyListeners();
      return Future.value(true);
    }

    return _confirmExit();
  }

  bool _onPopPage (Route route, dynamic result) {
    if (!route.didPop(result)) {
      return false;
    }

    if (_canPop()) {
      _pages.removeLast();
      return true;
    }

    return false;
  }

  Future<bool> _confirmExit() async {
     var result = await showDialog<bool>(
      context: navigatorKey.currentContext!,
      builder: (BuildContext context) {
        return AlertDialog(content: const Text('确定要退出吗？'),
        actions: [
          TextButton(onPressed: ()=>Navigator.pop(context,true), child: const Text('取消')),
          TextButton(onPressed: ()=>Navigator.pop(context,false), child: const Text('确定')),
        ],
        );
      }
    );
    print('点击_confirmExit  弹窗提示');
    return Future.value(true);
  }

  // 判断page
  bool _canPop () {

    if (_pages.length > 1) return true;

    return false;
  }


  Future<Object?> push ({required String name, dynamic args}) async{
    _boolResultComplete = Completer<Object?>();
    _pages.add(_createPage(RouteSettings(name: name, arguments: args)));
    // 上面不会自动发生响应去更新，然后通过下面通知更新
    notifyListeners();
    return _boolResultComplete.future;
  }


  MaterialPage _createPage(RouteSettings routeSettings) {
    Widget? page;
    var args = routeSettings.arguments;
    switch (routeSettings.name) {
      case mainPage:
        page = const MyHomePage(title: 'this is just a test');
        break;
      case secondPage:
        String param = routeSettings.arguments?.toString()?? '';
        page = FinancePage(params: param);
        break;
      case playerPage:
        String param = routeSettings.arguments?.toString()?? '';
        page = PlayerPage(url: param,);
        break;
      case videoListPage:
        page  = VideoList();
        break;
      case minePage:
        page = MinePage();
        break;
      case cameraPage:
        page = CameraPage();
        break;
      case photoPicker:
        String? url = '';
        String height = '';
        String width = '';
        if (args is Map<String, String>) {
          url = args[MyRoute.key_url];
          width = args[MyRoute.key_width]??width;
          height = args[MyRoute.key_height]??height;
        }
        page = PhotoPicker(url!);
        break;
      default:
        page = const Scaffold();
    }

    return MaterialPage(child: page,
      key: Key(routeSettings.name!) as LocalKey,
      name: routeSettings.name,
    arguments: routeSettings.arguments);
  }

}